package com.tianpengtech.admin.task;
import java.math.BigDecimal;
import java.util.*;

import com.jfinal.plugin.activerecord.Page;
import com.tianpengtech.common.util.XxxUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.tianpengtech.admin.AbstractAdminController;
import com.tianpengtech.admin.IAdminOpt;
import com.tianpengtech.admin.InitInterceptor;
import com.tianpengtech.common.GlobalConfigConstant;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.fairorder.FairOrder;
import com.tianpengtech.common.model.feedback.FeedBack;
import com.tianpengtech.common.model.moneylog.MoneyLog;
import com.tianpengtech.common.model.opertion.Opertion;
import com.tianpengtech.common.model.task.Task;
import com.tianpengtech.common.model.task.TaskCVS;
import com.tianpengtech.common.model.task.TaskCount;
import com.tianpengtech.common.model.task.TaskWh;
import com.tianpengtech.common.model.taskscreenshot.TaskScreenShot;
import com.tianpengtech.common.util.JsonUtil;
import com.tianpengtech.common.util.SendSmsMsg;
import com.tianpengtech.front.mobile.task.TaskCalculateService;
/**
* 路由配置地址：add("/admin/task", TaskAdminController.class, "/admin/task");
* 数据库映射地址：arp.addMapping(Task.dao.tableName(),Task.class);
*/
@Before(InitInterceptor.class)
@RequiresAuthentication
public class TaskAdminController extends AbstractAdminController{
	private IAdminOpt opt = new TaskAdminServiceImpl();
	@Override
	protected void config() {
		this.clazz=Task.class;
		this.service=new TaskAdminServiceImpl();
	}

	@Override
	public void beforeAdd() {

	}

	@Override
	public void beforeAdd(Model< ? > model) throws ValidateException {

	}

	@Override
	public void beforeQueryById(Model<?> model, int id) {

	}

	@Override
	public void beforeUpdate(Model< ? > model) throws ValidateException {

	}

	@Override
	public void beforeDelete(Model< ? > model) {

	}

	
	/**
	 * 审核通过
	 */
	public void  pass(){
		int id = getParaToInt(Task.ID,0);
		try {
			opt.changeStatus(getModel(Task.class), id, Task.STATUS_SUCCESS, Kv.create());
			renderJson(JsonUtil.printSuccess("操作成功"));
		} catch (ValidateException e) {
			renderJson(JsonUtil.printError(e.getMessage()));
		}
	}
	
	/**
	 * 拒绝理由填写页面
	 */
	public void  toRefuse(){
		int id = getParaToInt(Task.ID,0);
		setAttr("task",this.service.queryById(getModel(Task.class), id));
		renderTemplate("task-reason.html");
	}
	
	/**
	 * 审核不通过
	 */
	public void  unpass(){
		Task task = getModel(Task.class);
		String content = getPara(Opertion.CONTENT);
		Kv kv = Kv.by(Opertion.CONTENT, content);
		try {
			opt.changeStatus(task, task.getLong(Task.ID), Task.STATUS_FAILURE, kv);
			renderJson(JsonUtil.printSuccess("操作成功"));
		} catch (ValidateException e) {
			renderJson(JsonUtil.printError(e.getMessage()));
		}
	}

	@Override
	public void parsePageRecord(Object results) {
		Task task = (Task)results;
		task.set(Task.STATUS, task.status());
		task.set(Task.EXTENSION_TYPE, task.type());
		task.set(Task.TASK_PRICE,"￥"+TaskCalculateService.ME.calculateTaskTotalFee(task));
	}

	
	public void showDetail(){
		int id = getParaToInt(Task.ID, GlobalConfigConstant.DEFAULT_VALUE_ZERO);
		setAttr("task", this.service.queryById(getModel(Task.class), id));
		String sql="select * from "+FairOrder.dao.tableName()+" where obj_id=? limit 1 ";
		setAttr("order",FairOrder.dao.findFirst(sql,id));
		renderTemplate("task-detail.html");
	}
	
	public void payMoney(){
		int task_id = getParaToInt("task_id");
		int fair_id = getParaToInt("fair_id");
		String sql="select * from "+TaskWh.dao.tableName()+" where task_id=? and wh_id=?";
		TaskWh taskWh = TaskWh.dao.findFirst(sql,task_id,fair_id);
		double actualFee=0;
		if(taskWh!=null){
			long click_num =taskWh.getLong(TaskWh.CLICK_NUM);
			Task task = Task.dao.findById(task_id);
			setAttr("actualFee",TaskCalculateService.ME.IShouldPayHowMuchMoney(click_num, task));
			setAttr("click_num",click_num);
			setAttr("task",task);
			setAttr("totalFee",TaskCalculateService.ME.calculateTaskTotalFee(task));
		}else{
			setAttr("click_num",0);
			setAttr("actualFee",(int)actualFee);
		}
		setAttr("task",Task.dao.findById(task_id));
		Fair fair = Fair.dao.findById(fair_id);
		setAttr("fair_id",fair_id);
		setAttr("fair",fair);
		renderTemplate("task-fee.html");
	}
	
	
	
	@Before(Tx.class)
	public void accept(){
		int task_id = getParaToInt("task_id");
		int fair_id = getParaToInt("fair_id");
		String fee = getPara("price");
		String sql="select * from "+TaskWh.dao.tableName()+" where task_id=? and wh_id=? limit 1";
		TaskWh taskWh = TaskWh.dao.findFirst(sql,task_id,fair_id);
		
		int status = taskWh.getInt(TaskWh.STATUS);
		if(status==Task.STATUS_COMPLETED){
			renderJson(JsonUtil.printError("当前任务已经被结算验收，请勿重复操作"));
			return;
		}else{
			
			//为当前网红增加任务相关费用信息，以及增加流水日志信息
			Task task = Task.dao.findById(task_id);
			Fair fair = Fair.dao.findById(fair_id);
			
			final Float price=task.getFloat(Task.TOTAL_FEE);
			
			final Float acturalFee=Float.parseFloat(fee);
			if(acturalFee>price){
				renderJson(JsonUtil.printError("实际支付金额不允许超过任务预算"));
				return;
			}
			
			taskWh.set(TaskWh.STATUS, Task.STATUS_COMPLETED);
			taskWh.update();
			Double d = fair.get(Fair.MONEY);
	          if (d==null){
	              d=0D;
	          }
	          double sum=d.doubleValue()+acturalFee.doubleValue();
	          fair.set(Fair.MONEY,sum);
	          fair.update();
			
	        MoneyLog ml = new MoneyLog();
            ml.set(MoneyLog.WH_ID,fair.get(Fair.ID));
            ml.set(MoneyLog.OPERID,task.getLong(Task.ID));
            ml.set(MoneyLog.STATE, MoneyLog.STATE_ADD);
            ml.set(MoneyLog.TYPE,MoneyLog.TYPE_RENWU);
            ml.set(MoneyLog.DELETETAG,MoneyLog.STATUS_SUCCESS);
            ml.set(MoneyLog.MONEY,acturalFee.doubleValue());
            ml.set(MoneyLog.DESCRIPTION,"任务完成："+task.getStr(Task.TASK_TITLE));
            ml.save();
            
            //同步收益表信息
            
            //if(SysConfigDao.ME.isSendTaskSMS()){
            	//发送短信
             
            if(fair.getInt(Fair.SMS_SET)==1){
            	SendSmsMsg.sendPayFeeInfo(fair.getStr(Fair.MOIBILE),task.getStr(Task.TASK_TITLE),
                		taskWh.getLong(TaskWh.CLICK_NUM)+"", acturalFee+"",SendSmsMsg.TEMPLATE_PAY_FEE);
            	}
            
            //}
            renderJson(JsonUtil.printSuccess("操作成功"));
			return;
		}
	}
	
	
	
	public void queryProcessById(){
		int taskId = getParaToInt("id",0);
		String sql= "select t2.nick_name,t1.* from "+TaskWh.dao.tableName()+" as t1,fair_wh as t2 where t1.task_id=? and t1.wh_id = t2.id";
		List<TaskWh> taskWh = TaskWh.dao.find(sql,taskId);
		for (TaskWh each : taskWh) {
			sql="select count(id) as click from "+TaskCount.dao.tableName()+" where type=? and task_id=? and wh_id=?";
			TaskCount t= TaskCount.dao.findFirst(sql,TaskCount.TYPE_DEV,taskId,each.getInt(TaskWh.WH_ID));
			each.put("click_dev",t.getLong("click")); 
			
			sql="select count(id) as click from "+TaskCVS.dao.tableName()+" where type=? and task_id=? and wh_id=?";
			TaskCVS cvs= TaskCVS.dao.findFirst(sql,TaskCount.TYPE_DEV,taskId,each.getInt(TaskWh.WH_ID));
			each.put("cvs_dev",cvs.getLong("click")); 
		}
		setAttr("taskWh", taskWh);
		renderTemplate("task-wh-detail.html");
	}
	
	
	public void taskCountSetting(){
		String sql = "select * from fair_sys_setting where type=?";
		setAttr("setting",Db.findFirst(sql,"TASK_COUNT_MODE"));
		renderTemplate("task-count-setting.html");
	}

	/**
	 * 任务数据分析
	 */
	public void taskDataAnalysis(){
		String whSql = "SELECT  id, nick_name nickName  FROM  fair_wh  WHERE status =2  ORDER BY convert(nick_name USING gbk)";
		List<Record> whList = Db.find(whSql);
		List whdata = new ArrayList();
		for (Record record : whList){
			Map map = new HashMap();
			map.put("id",record.getLong("id"));
			map.put("nickName",record.getStr("nickName"));
			whdata.add(map);
		}
		String taskSql = "SELECT  id,  task_title taskTitle   FROM  fair_task   ";
		List<Record> taskList = Db.find(taskSql);
		List taskdata = new ArrayList();
		for (Record record : taskList){
			Map map = new HashMap();
			map.put("id",record.getLong("id"));
			map.put("taskTitle",record.getStr("taskTitle"));
			taskdata.add(map);
		}
		setAttr("whList", whdata);
		setAttr("taskList", taskdata);
		renderTemplate("task-data-analysis.html");
	}




	public void updateSetting(){
		int mode = getParaToInt("task_count_mode",0);
		int is_send_task_sms = getParaToInt("is_send_task_sms",0);
		int is_task_fair = getParaToInt("is_task_fair",1);
		int id = getParaToInt("id",0);
		Record record = new Record();
		record.set("id", id);
		record.set("task_count_mode", mode);
		record.set("is_send_task_sms", is_send_task_sms);
		record.set("is_task_fair", is_task_fair);
		Db.update("fair_sys_setting", record);
		renderJson(JsonUtil.printSuccess("保存成功"));
	}

	/**
	 * 任务状态详情页
	 */
	public void showStatus(){
		int id = getParaToInt(Task.ID, GlobalConfigConstant.DEFAULT_VALUE_ZERO);
		List statusList = new ArrayList();
		Map startMap = new HashMap();
		startMap.put("statusId",Task.STATUS_START);
		startMap.put("status","任务开始");
		Map endMap = new HashMap();
		endMap.put("statusId",Task.STATUS_COMPLETED);
		endMap.put("status","任务完成");
		statusList.add(startMap);
		statusList.add(endMap);
		setAttr("statusList", statusList);
		setAttr("id", id);
		renderTemplate("task-status-change.html");
	}

	/**
	 * 更改任务状态
	 */
	public void changeStatus(){
		int id = getParaToInt(Task.ID, GlobalConfigConstant.DEFAULT_VALUE_ZERO);
		int statusId = getParaToInt("statusId");
		String sql = "update fair_task set status=? where id=?";
		Db.update(sql, statusId, id);
		renderJson(JsonUtil.printSuccess("保存成功"));
	}

	public void gettaskDataAnalysisList() {
		int start = getParaToInt(GlobalConfigConstant.PARAM_NAME_START,
				GlobalConfigConstant.DEFAULT_VALUE_PAGENUM);
		int length = getParaToInt(GlobalConfigConstant.PARAM_NAME_LENGTH,
				GlobalConfigConstant.DEFAULT_VALUE_PAGESIZE);
		int draw = getParaToInt(GlobalConfigConstant.PARAM_NAME_DRAW, GlobalConfigConstant.DEFAULT_VALUE_PAGENUM);
		String whId = getPara("whId");
		String taskId = getPara("taskId");
		List list = getTaskStatistical(whId, taskId);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("draw", draw);
		result.put("recordsTotal", list.size());
		result.put("recordsFiltered", list.size());
		if (list.size()>start && list.size()>=start+length){
			result.put("data", list.subList(start,start+length));
		}else if (list.size()>start &&list.size()<start+length){
			result.put("data",list.subList(start,list.size()));
		}else {
			result.put("data",list);
		}
		renderJson(result);
	}

	//后台任务统计
	public List getTaskStatistical(String wId, String tId) {
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT  ");
		sb.append(" c.id,  ");
		sb.append(" c.wh_id whId,  ");
		sb.append(" c.task_id taskId,  ");
		sb.append(" c.os_name osName,  ");
		sb.append(" c.city,  ");
		sb.append(" t.task_title taskTitle,  ");
		sb.append(" w.nick_name nickName,  ");
		sb.append(" tw.click_num clickNum,  ");
		sb.append(" tw.cvs_num cvsNum,  ");
		sb.append(" count( * ) count   ");
		sb.append("FROM   ");
		sb.append(" (SELECT * from fair_task_count  GROUP BY wh_id, task_id, ip,user_agent) c     ");
		sb.append(" INNER JOIN fair_wh w ON c.wh_id = w.id   ");
		sb.append(" INNER JOIN fair_task t ON c.task_id = t.id   ");
		sb.append(" INNER JOIN fair_task_wh tw ON tw.wh_id = c.wh_id   ");
		sb.append(" AND tw.task_id = c.task_id    ");
		if (wId != null || tId != null){
			sb.append("WHERE    ");
			if (wId != null && tId != null){
				sb.append(" t.id = ?    ");
				sb.append(" AND w.id = ? ");
			}else if (wId != null && tId == null){
				sb.append(" w.id = ? ");
			}else if (wId == null && tId != null){
				sb.append(" t.id = ?    ");
			}

		}
		sb.append("GROUP BY    ");
		sb.append(" c.wh_id,    ");
		sb.append(" c.task_id,    ");
		sb.append(" c.os_name    ");
		sb.append("ORDER BY    ");
		sb.append(" c.task_id,   ");
		sb.append(" c.wh_id    ");
		List<Record> list;
		if (tId != null && wId != null){
			list = Db.find(sb.toString(), tId, wId);
		}else if (tId == null && wId != null){
			list = Db.find(sb.toString(), wId);
		}else if (tId != null && wId == null){
			list = Db.find(sb.toString(), tId);
		} else {
			list = Db.find(sb.toString());
		}


		List<Map> taskList = new ArrayList<>();
		Integer lastTaskId = null ;
		Integer lastWhId = null;
		for (Record record : list){
			Map map;
			Integer taskId = record.getInt("taskId");
			Integer whId = record.getInt("whId");
			if (lastTaskId != null && lastWhId != null && lastTaskId.equals(taskId)  && lastWhId.equals(whId) ){
				map = taskList.get(taskList.size()-1);
				String osName = getOsName(record.getStr("osName"));
				if (osName != null) map.put(osName, record.getLong("count"));
			}else {
				map = new HashMap();
				lastTaskId = taskId;
				lastWhId = whId;
				BigDecimal money = getTaskMoney(whId,taskId);
				String osName = getOsName(record.getStr("osName"));
				map.put("id", record.getInt("id"));
				map.put("money",money);
				map.put("taskTitle", record.getStr("taskTitle"));
				map.put("nickName", record.getStr("nickName"));
				map.put("clickNum", record.getInt("clickNum"));
				map.put("cvsNum", record.getInt("cvsNum"));
				map.put("iOS", 0L);
				map.put("Android", 0L);
				map.put("Windows", 0L);
				map.put("OS", 0L);
				if (osName != null) map.put(osName, record.getLong("count"));
				map.put("city", record.getStr("city"));
				taskList.add(map);
			}

		}
		return  taskList;

	}
	private BigDecimal getTaskMoney(Integer whId, Integer taskId){
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT  ");
		sb.append(" m.money   ");
		sb.append("FROM  ");
		sb.append(" fair_wh_moneylog m   ");
		sb.append("WHERE  ");
		sb.append(" m.wh_id = ?  ");
		sb.append(" AND m.operid = ?  ");
		sb.append(" AND m.state = 1  ");
		Record record = Db.findFirst(sb.toString(), whId, taskId);
		if (record != null){
			return record.getBigDecimal("money");
		}else {
			return new BigDecimal(0);
		}
	}

	private String getOsName(String name){
		String os_name_iOS      = "iOS";
		String os_name_android  = "Android";
		String os_name_windows  = "Windows";
		String os_name_OS       = "OS";
		String osName = null;
		if (name != null){
			if (name.startsWith(os_name_iOS)){
				osName = os_name_iOS;
			}else if (name.startsWith(os_name_android)){
				osName = os_name_android;
			}else if (name.startsWith(os_name_OS)){
				osName = os_name_OS;
			}else if (name.startsWith(os_name_windows)){
				osName = os_name_windows;
			}
		}
		return osName;
	}

}

	